package agent

import (
	"fmt"
	"time"

	"gitee.com/shiwjlinux/arm/apps/game"
	"gitee.com/shiwjlinux/arm/common"
)

func (i *InstanceAgent) List3ThPackages(index int) *game.GameSet {
	gameSet := game.NewGameSet()
	var cmd string
	// 执行命令获取第三方包列表
	if common.IsAndroid() {
		cmd = fmt.Sprintf(`source /data/cce/bin/setupenv.sh &>/dev/null;docker exec con%d sh /data/welink/ops/getPkgsInfo.sh`, index)
	} else {
		cmd = fmt.Sprintf(
			`adb connect %s >/dev/null 2>&1 ; 
			adb -s %s shell 'source /data/cce/bin/setupenv.sh &>/dev/null; 
			docker exec con%d sh /data/welink/ops/getPkgsInfo.sh'`,
			fmt.Sprintf("%s:%s", TestAgentIp, "5555"),
			fmt.Sprintf("%s:%s", TestAgentIp, "5555"),
			index)
	}

	// cmd := "ls"
	stdout, stderr, code, err := common.CmdWithTimeout(10*time.Second, "sh", "-c", cmd)

	if err != nil || code != 0 || stderr != "" {
		i.logger.Error().
			Any("error", err).
			Any("stdout", stdout).
			Any("stderr", stderr).
			Any("code", code).
			Str("cmd", cmd).
			Msg("Error executing command")
		return nil
	}
	// fmt.Println(stdout)

	err = gameSet.Parse(stdout)
	if err != nil {
		i.logger.Error().Err(err).Msg("failed to parse game set")
		return nil
	}
	gameSet.Total = int64(len(gameSet.Games))
	return gameSet
}

func (a *InstanceAgent) runReportGamesLoop() {
	ticker := time.NewTicker(gameTicker) // 使用 interval 作为报告间隔
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			if err := a.reportGames(); err != nil {
				a.logger.Error().Err(err).Msg("failed to report games")
			}
		case <-a.stopChan:
			return
		case <-a.ctx.Done():
			return
		}
	}
}

// reportGames 收集并报告游戏信息
func (a *InstanceAgent) reportGames() error {
	// 收集游戏信息的逻辑
	games, err := a.collectGameInfo()
	if err != nil {
		return fmt.Errorf("failed to collect game info: %v", err)
	}

	// 发送游戏信息的逻辑
	if err := a.sendGameInfo(games); err != nil {
		return fmt.Errorf("failed to send game info: %v", err)
	}

	a.logger.Info().Msg("games reported successfully")
	return nil
}

// collectGameInfo 收集游戏信息
func (a *InstanceAgent) collectGameInfo() ([]game.Game, error) {
	// TODO: 实现实际的游戏信息收集逻辑
	var games []game.Game
	// 示例：从某个 API 获取游戏信息
	// ...

	return games, nil
}

// sendGameInfo 发送游戏信息
func (a *InstanceAgent) sendGameInfo(games []game.Game) error {
	// TODO: 实现实际的游戏信息发送逻辑
	// 示例：将游戏信息发送到服务器
	// ...

	return nil
}
